require.async(['JqueryBase','UrlUtil','common','base64','ValidUtil','PageUtil'],function(window){

/** 服务信息全局对象 **/ 
var serveObj; 
/** 全局预约规格ID **/ 
var serveStandardId; 
/** 当前地区信息 **/ 
var cityCode = CookieUtil.get(Constant.CITY_CODE);
var cityName = CookieUtil.get(Constant.CITY_NAME); 
var lon = CookieUtil.get(Constant.CITY_LON);
var lat = CookieUtil.get(Constant.CITY_LAT);  
/** 加载服务信息 **/ 
(function getServe(){ 
	if(!cityCode) {
		layer.alert("定位城市失败，请刷新后重试！");
		return;
	}
	
	var id = UrlUtil.getUrlParam("id"),idIndex = id.indexOf('#');
	if(idIndex!=-1){
		id = id.substring(0,idIndex);
	}
	BaseUtil.get("eb/serve/front/getFrontServe",function(result){ 
		serveObj = result.data; 
		$("#serve_title").html(serveObj.serveName);
		
		$("#standard_list a").remove();
		var standardHTML = '<a class="car_a {checked}" href="javascript:{func}">{serveStandardName}</a>';
		var sdhtml = [];
		$.each(serveObj.serveStandard,function(idx,item){
			sdhtml.push(standardHTML.replaceAll("{serveStandardName}",item.serveStandardName).replaceAll("{func}","selectStandrad("+idx+")"));
		}); 
		//已售出
		$("#serve_record").html(serveObj.serveSold);
		//评价数
		$("#serve_comment").html(serveObj.evaluate);
		//好评率
		$("#serve_comment_rate").html(NumberUtil.round(serveObj.evaluateRate * 100) + "%");
		
		//规格列表
		$("#standard_list").append(sdhtml.join('')); 
		//服务介绍
		$("#servedesc").html(serveObj.description); 
		//服务详情
		$("#info_productComposition").html(serveObj.productComposition);
		$("#info_servename").html(serveObj.serveName);
		$("#info_servedesc").html(serveObj.description); 
		var info_charge = '';//'轿车（300元/60分钟）、SUV（320/80分钟）';
		$.each(serveObj.serveStandard,function(idx,item){
			$("#info_charge").append(item.serveStandardName+"( "+item.price+"元 /"+item.workMin+"分钟 ) &nbsp; "); 
		});   
		//用户评价
		getComments(serveObj.id); 
		//点击第一个规格
		selectStandrad(0);
		//小区列表
		getEstate(cityCode,null); 
	},{'id':id,"baiduCode":cityCode}); 
})();
/** 选择规格 **/
window.selectStandrad = function(index){    
	//规格ID赋值 
	serveStandardId = serveObj.serveStandard[index].id;
	//样式改变
	$.each($("#standard_list a"),function(idx,item){
		$(this).removeClass("cur");   
	});       
	$("#standard_list a")[index].className = 'car_a cur';     

	//金额改变  
	$("#serve_price").html(serveObj.serveStandard[index].price);
	
	//预览图改变
	$.each($("#showbox img[name=showboximg]"),function(idx,item){ 
		if(idx < serveObj.serveStandard[index].detailUrls.split(",").length){ 
			item.setAttribute("src",basePath+"/file/display/"+serveObj.serveStandard[index].detailUrls.split(",")[idx]);   
		} else {
			item.setAttribute("src",'');   
		}
	});      
	$("#showsum").html(''); 
	$.ljsGlasses.pcGlasses(showproduct);//方法调用，务必在加载完后执行
	$("#info_serveinfoimg").attr('src',basePath+"/file/display/"+serveObj.serveStandard[index].infoUrl); 
} 

/** 立即预约 **/
window.toServeOrderConfirm = function(id,estateId){ 
	var param = "estateId="+estateId+"&serveStandardId="+serveStandardId;  
	param = BASE64.encoder(param);  
	BaseUtil.loginRedirect("serve/auth/servicesure.html?sn="+param);   
}

/**百度地图功能开始*/
var map = new BMap.Map("l-map"); 
var myGeo = new BMap.Geocoder();
/** 地图默认居中 **/
var zoomLongitude = 120.310679,zoomLatitude = 31.837425;//默认江阴市
/** 小区列表 **/
window.getEstate = function(cityCode,areaId){ 
	
	$("#serve_area_ul").html('');//清空小区列表
	map.clearOverlays();//清空覆蓋物
	
	var params = {}; 
	if(ValidUtil.isNotBlank(areaId)){   //下拉查询参数
		areaId = document.getElementById('district').value; 
		cityId = document.getElementById('city').value;  
		if(ValidUtil.isNotBlank(areaId)){ 
			params = {"longitude":lon,"latitude":lat,'areaId':areaId}   
		} else if(ValidUtil.isNotBlank(cityId)) { 
			params = {"longitude":lon,"latitude":lat,'cityId':cityId} 
		} else { 
			params = {"longitude":lon,"latitude":lat}   
		} 
	} else { //初始化参数
		params = {"longitude":lon,"latitude":lat,'baiduCode':cityCode}//
	}  
	BaseUtil.get("im/estate/front/pageEstate",function(result){ 
		var estateObj = result.data;
		var estateHTML = '<li onclick="{lifunc}" class="clearfix" onmouseover="this.style.backgroundColor=\'#f8f8f8\'" onmouseout="this.style.backgroundColor=\'\'" style="cursor: pointer;"><i class="location">{idx}</i><span><p class="position01">{estatename}服务点</p><p class="addr01">{addressinfo}</p></span><a href="javascript:void(0)" onclick="{spurl}" class="a_btn">立即预约</a></li>';
		var estateARRAY = [],addressARRAY = [];
		var addressLNL = [];//小区经纬度集合
		var namesLNL = [];//小区地址集合
		$.each(estateObj.items,function(idx,item){ 
			if(idx == 0){
				zoomLongitude = estateObj.items[0].longitude;
				zoomLatitude = estateObj.items[0].latitude;  
			} 
			estateARRAY.push(estateHTML.replaceAll("{spurl}","toServeOrderConfirm("+serveObj.id+","+item.id+")")
					.replaceAll("{idx}",idx+1)
					.replaceAll("{estatename}",item.estateName)
					.replaceAll("{addressinfo}",item.provinceName+item.cityName+item.areaName+item.address)
					.replaceAll("{lifunc}",'window.zoom(\''+item.longitude+'\',\''+item.latitude+'\')')
					); 
			addressARRAY.push(item.provinceName+item.cityName+item.areaName+item.address);

			addressLNL.push(new BMap.Point(item.longitude,item.latitude)); 
			namesLNL.push(item.provinceName+item.cityName+item.areaName+item.address);  
		});   
		$("#serve_area_ul").append(estateARRAY.join('')); 
		
		
		estateMap(addressLNL,namesLNL); 
	},params);   
} 

function estateMap(adds,names){
	map.centerAndZoom(new BMap.Point(zoomLongitude,zoomLatitude), 14);
	map.enableScrollWheelZoom(true);
	/*var adds = [
		new BMap.Point(116.345867,39.998333),
		new BMap.Point(116.403472,39.999411),
		new BMap.Point(116.307901,40.05901)
	];*/ 
	for(var i = 0; i<adds.length; i++){
		var marker = new BMap.Marker(adds[i]);  
		map.addOverlay(marker);
		marker.setLabel(new BMap.Label((i+1)+":"+names[i],{offset:new BMap.Size(20,-10)}));
	}
}
// 经纬度在地图上居中显示
window.zoom = function(longitude,latitude){//
	map.centerAndZoom(new BMap.Point(longitude,latitude), 14);  
} 
//逆解析
var index = 0;
function bdGEO(){	
	var pt = adds[index];
	geocodeSearch(pt);
	index++;
}
//逆解析
function geocodeSearch(pt){
	if(index < adds.length-1){
		setTimeout(window.bdGEO,400);
	} 
	myGeo.getLocation(pt, function(rs){
		var addComp = rs.addressComponents;
		document.getElementById("result").innerHTML += index + ". " +adds[index-1].lng + "," + adds[index-1].lat + "："  + "商圈(" + rs.business + ")  结构化数据(" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber + ")<br/><br/>";
	});
}
/**百度地图功能结束*/

//加载合作城市
 BaseUtil.get("eb/area/front/pageArea",function(result){ 
	 
	var areaData = result.data; 
	$("#city option").remove();   
	$.each(areaData.items,function(idx,item){  
		if(cityCode == item.id){
			$("#city").append('<option value="'+item.cityId+'" selected>'+item.name+'</option>');
			getArea(item.cityId);  
		} else { 
			$("#city").append('<option value="'+item.cityId+'">'+item.name+'</option>');
		}
	});  
},{}); 
window.getArea = function(cityId){ 
	 BaseUtil.get("eb/area/front/pageArea",function(result){ 
		 var areaData = result.data;  
		 $("#district option:gt(0)").remove(); 
		 $.each(areaData.items,function(idx,item){  
			 $("#district").append('<option value="'+item.id+'">'+item.areaName+'</option>');
		 });
	 },{"id":0,"parentId":cityId}); 
	 
 }
//加载用户评价
var commentsPage = 1,commentsPageSize = 5;
function getComments(serveId){    	
	$("#usercomment").html(''); 
	BaseUtil.get("eb/comments/front/pageComments",function(result){ 
		if(result.data.items.length > 0){
			//用户评价
			var usercommentHTML = '<li class="clearfix mt20"><div class="userimg"><img style="display: block; width: 200px; height: 200px;" src="{imgsrc}"></div><div class="userinfo"><h4>{customername}</h4><p class="mb5"><span class="staricon">{level}</span><span class="staricon" style="margin-left: 30px"> {estateName}</span></p><p class="time">{content}</p><p class="time">发表于 {evtime}</p></div></li>';
			var uchtml = [];
			$.each(result.data.items,function(idx,item){
				var levels = '';
				for(var i = 0;i< item.level;i++){
					levels += '<img src="{levelUrl}">';
				} 
				uchtml.push(usercommentHTML.replaceAll("{estateName}",item.estateName).replaceAll("{level}",levels).replaceAll("{evtime}",DateUtil.timeToString(item.createTime,DateUtil.TIME)).replaceAll("{content}",item.content).replaceAll("{customername}",item.customerName?item.customerName:'**').replaceAll("{imgsrc}",basePath+"/file/display/"+ item.avatarUrl).replaceAll("{levelUrl}",basePath+'/front/images/starsy.png'));
			});   
			$("#usercomment").append(uchtml.join(''));  
			//分页信息
			$("#usercommentpage").html(PageUtil.getHtml(result.data.total,commentsPage,5,commentsPageSize));     
		} else {
			$("#usercomment").html("此服务暂无用户评价");      
		}
	},{"start":(commentsPage-1)*commentsPageSize,"limit":commentsPageSize,"serveId":serveId});   
}

//分页点击回调
window.page = function(page){   
	commentsPage = page;
	getComments(serveObj.id);  
}


var showproduct = {
		"boxid":"showbox",
		"sumid":"showsum",
		"boxw":465,//宽度,该版本中请把宽高填写成一样
		"boxh":268,//高度,该版本中请把宽高填写成一样
		"sumw":83,//列表每个宽度,该版本中请把宽高填写成一样
		"sumh":52,//列表每个高度,该版本中请把宽高填写成一样
		"sumi":10,//列表间隔
		"sums":5,//列表显示个数 
		"sumsel":"sel",
		"sumborder":1,//列表边框，没有边框填写0，边框在css中修改
		"lastid":"showlast",
		"nextid":"shownext"
};//参数定义	  
	
//加载省市区并绑定change事件 
/*CityUtil.provinceSelect("province","city","district");
$("#province").change(function(){ 
	CityUtil.citySelect("province","city","district");
});  
$("#city").change(function(){
	CityUtil.districtSelect("province","city","district");
}); */
/**服务大图预览*/
window.queryImage = function(obj){
	layer.open({
	  type: 1,
	  title: false,
	  closeBtn: 0,
	  area: ['1000px', document.body.clientHeight-20],//'516px',  
	  skin: 'layui-layer-nobg', //没有背景色
	  shadeClose: true,
	  content: obj
	}); 
}
});   

